<template>
  <div v-loading="loading" class="noteView">
    <split-pane :default-percent="18" :min-percent="12" split="vertical" @resize="resize">
      <template slot="paneL">
        <div class="expand-layout">
          <!-- 新建组/笔记 -->
          <div class="more-dir">
            <ul>
              <li class="dir-name" style="border-right: 1px solid #ececec;">
                <div>
                  <el-button
                    :loading="addGroupBtnLoading"
                    type="text"
                    style="color: #555;"
                    @click="addGroup"
                  >{{ $t('新建分组') }}</el-button>
                </div>
              </li>
              <li style="border-right: 1px solid #ececec;">
                <div class="dir-name on">
                  <el-dropdown @command="addText($event)">
                    <el-button type="text" :loading="addTextBtnLoading" style="color: #555;" @click="addText('')">
                      {{ $t('新建笔记') }}<i class="el-icon-arrow-down el-icon--right" />
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="">{{ $t('个人笔记') }}</el-dropdown-item>
                      <el-dropdown-item
                        v-for="item of createTypeOptions"
                        :key="item.id"
                        :command="item.dictValue"
                      >{{ item.dictLabel }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </li>
            </ul>
          </div>
          <el-tree
            :data="noteData"
            :props="defaultProps"
            node-key="id"
            :highlight-current="true"
            :default-expand-all="false"
            :default-expanded-keys="['notes']"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node tree-node-btn">
              <span v-if="editId !== data.id" :style="{ 'font-size': '13px', 'font-weight': (prohibitClickingIds.includes(data.id) ? 'bold': 'normal') }" @click="recordNodes(data)">
                <span v-if="dirIds.includes(data.id)">{{ data.name }}</span>
                <span v-else-if="data.belong === 'notes'" @click="viewNotes(data.id, true)">{{ data.name }}</span>
                <span v-else-if="data.belong === 'tag'" @click="viewTag(data, true)"><span style="margin-left: 5px;">{{ data.name }}</span></span>
                <span v-else-if="data.id === 'share'" @click="viewShare(true)">{{ data.name }}</span>
                <span v-else-if="data.id === 'follow'" @click="viewFollow(true)">{{ data.name }}</span>
                <span v-else @click="viewText(data)">
                  <i class="iconfont icon-a-chengjiantubiaoku_wendang11" /><span style="margin-left: 5px;">{{ data.name }}</span>
                </span>
              </span>
              <el-input
                v-else
                v-model="data.name"
                size="mini"
                style="width: 140px;"
                @keyup.enter.native="$event.target.blur()"
                @blur="blurGroup(data)"
              />
              <span v-if="data.belong === 'notes' && data.name !== '未分组' && data.id !== 'notes'" style="position: absolute;right: 10px;">
                <template>
                  <el-button
                    type="text"
                    size="mini"
                    @click="editGroup(data)"
                  ><i class="el-icon-edit" /></el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="removeGroup(data)"
                  ><i class="el-icon-delete" /></el-button>
                </template>
              </span>
            </span>
          </el-tree>
        </div>
      </template>
      <template slot="paneR">
        <!-- 中间列 笔记 -->
        <split-pane :default-percent="26.2" :min-percent="12" split="vertical">
          <template slot="paneL">
            <div class="flexible-list-left">
              <div class="list-search">
                <div style="display: flex">
                  <el-tooltip class="item" effect="dark" placement="left-end">
                    <div slot="content">
                      {{ $t('回车快速搜索') }}<br>
                      {{ $t('清除搜索重新加载') }}
                    </div>
                    <el-select v-model="selectSearch" class="el-search-select-left" size="mini" style="width: 30%;" @change="changeSelectQuery">
                      <el-option :label="$t('标题')" value="title" />
                      <el-option :label="$t('内容')" value="text" />
                      <el-option :label="$t('标签')" value="tag" />
                      <el-option :label="$t('类型')" value="type" />
                      <el-option :label="$t('标记')" value="color" />
                    </el-select>
                  </el-tooltip>
                  <el-input
                    v-if="['title', 'text'].includes(selectSearch)"
                    v-model="inputSearch"
                    size="mini"
                    clearable
                    class="el-search-select-right"
                    style="width: 70%;"
                    :placeholder="$t('请输入关键词')"
                    @keyup.enter.native="querySearch"
                    @clear="clearQuerySearch"
                  />
                  <el-select
                    v-else
                    v-model="inputSearch"
                    filterable
                    clearable
                    style="width: 70%;"
                    size="mini"
                    class="el-search-select-right"
                    :placeholder="$t('请输入关键词')"
                    @keyup.enter.native="querySearch"
                    @change="querySearch"
                    @clear="clearQuerySearch"
                  >
                    <el-option v-if="selectSearch === 'color'" value="">
                      <span style="font-size: 18px;">○<span style="font-size: 14px;position: absolute;">{{ $t('无') }}</span><span style="position: absolute;left: 26px;">/</span></span>
                    </el-option>
                    <el-option v-for="item in querySelectOption" :key="item.value" :value="item.value" :label="item.label">
                      <span v-if="selectSearch === 'color'" :style="{ 'color': item.color, 'font-size': '30px' }">●<span style="font-size: 14px;position: absolute;">{{ item.label }}</span></span>
                      <span v-else>{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </div>
                <el-dropdown v-if="false" trigger="click">
                  <i class="el-icon-s-operation" />
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>{{ $t('标题') }}</el-dropdown-item>
                    <el-dropdown-item>{{ $t('摘要') }}</el-dropdown-item>
                    <el-dropdown-item divided>{{ $t('时间正序') }}</el-dropdown-item>
                    <el-dropdown-item divided>{{ $t('时间倒序') }}</el-dropdown-item>
                    <el-dropdown-item divided>{{ $t('类型') }}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="list-view-item">
                <ul
                  v-infinite-scroll="load"
                  class="list"
                  :infinite-scroll-disabled="disabled"
                  :infinite-scroll-distance="100"
                >
                  <!-- 笔记列表 -->
                  <li v-for="(text) in textList" :key="text.id" class="list-li">
                    <div class="title" @click="viewText(text)">
                      <div class="file-name-wrap">
                        <i class="iconfont icon-a-chengjiantubiaoku_wendang11" />
                        <div class="file-name">{{ text.title }}</div>
                      </div>
                      <div class="date-size">
                        <span class="file-date"> {{ parseTime(text.updateTime, '{y}-{m}-{d} {h}:{i}') }}  </span>
                        <span class="file-size"><i :class="text.type" /></span>
                        <span
                          v-if="!isEmpty(text.color)"
                          class="file-size"
                          :style="{ 'color': text.color, 'ont-weight': 'lighter', 'font-size': '30px', 'position': 'absolute', 'bottom': '7px', 'margin-left': '5px' }"
                        >●</span>
                      </div>
                    </div>
                    <div style="position: absolute;right: 10px;bottom: 0;">
                      <el-button v-if="text.collection === 'N'" type="text" class="el-icon-star-off" style="font-size: 13px;" @click="addCollection(text)" />
                      <el-button v-if="text.collection === 'Y'" type="text" class="el-icon-star-on" style="font-size: 18px;color: orange;" @click="delCollection(text)" />
                      <el-dropdown trigger="click">
                        <el-button :title="$t('移动笔记')" :disabled="$store.state.user.userId !== text.userId" type="text" class="el-icon-help" style="font-size: 13px;margin-left: 5px;" />
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item v-for="item in moveTextSelect" :key="item.id" :disabled="item.id === text.groupId" @click.native="moveText(text, item)">{{ item.name }}</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                      <el-button :disabled="$store.state.user.userId !== text.userId" type="text" :loading="delTextBtnLoading" class="el-icon-delete" style="font-size: 13px;margin-left: 5px;" @click="delText(text)" />
                    </div>
                  </li>
                </ul>
                <p v-if="scrollLoading" style="font-size: 14px;text-align: center;">{{ $t('加载中') }}...</p>
                <p v-if="noMore && textList.length >= 20" style="font-size: 14px;text-align: center;">{{ $t('没有更多了') }}</p>
                <div v-if="textList.length === 0 && !loading">
                  <div v-if="!isCurrentFollow && !isCurrentShare" style="text-align: center;margin-top: 65%;">
                    <el-dropdown @command="addText($event)">
                      <el-button :loading="addTextBtnLoading" size="mini" type="primary" @click="addText('')">
                        {{ $t('新建笔记') }}
                      </el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="">{{ $t('个人笔记') }}</el-dropdown-item>
                        <el-dropdown-item
                          v-for="item of createTypeOptions"
                          :key="item.id"
                          :command="item.dictValue"
                        >{{ item.dictLabel }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                  <div v-else style="text-align: center;margin-top: 50%;">
                    <svg style="width: 100px;height: 100px" t="1694107653047" class="icon" viewBox="0 0 1567 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2625" xmlns:xlink="http://www.w3.org/1999/xlink" width="306.0546875" height="200"><path d="M156.662278 699.758173h21.097186A10.444152 10.444152 0 0 1 187.994733 710.202325c0 5.765172-4.490985 10.444152-10.235269 10.444152H156.662278v21.097186A10.444152 10.444152 0 0 1 146.218126 751.978932a10.277045 10.277045 0 0 1-10.444152-10.235269V720.646477H114.676787A10.444152 10.444152 0 0 1 104.441518 710.202325c0-5.765172 4.490985-10.444152 10.235269-10.444152H135.773974v-21.097187A10.444152 10.444152 0 0 1 146.218126 668.425717c5.765172 0 10.444152 4.490985 10.444152 10.235269v21.097187z m1378.628042-83.553215v-21.097186A10.277045 10.277045 0 0 0 1524.846168 584.872503a10.444152 10.444152 0 0 0-10.444152 10.235269v21.097186h-21.097186a10.277045 10.277045 0 0 0-10.235269 10.444152c0 5.598065 4.595427 10.444152 10.235269 10.444152h21.097186v21.097187c0 5.744284 4.67898 10.235269 10.444152 10.235268a10.444152 10.444152 0 0 0 10.444152-10.235268V637.093262h21.097187c5.744284 0 10.235269-4.67898 10.235268-10.444152a10.444152 10.444152 0 0 0-10.235268-10.444152H1535.29032zM776.460024 960.861969H250.596979A20.80475 20.80475 0 0 1 229.77134 939.973665c0-11.530344 9.462402-20.888304 20.825639-20.888303h94.728457A83.010119 83.010119 0 0 1 334.212859 877.413196v-605.96969A83.49055 83.49055 0 0 1 417.849627 187.994733H480.430984V167.001988A83.49055 83.49055 0 0 1 564.067752 83.553215h501.152182A83.448773 83.448773 0 0 1 1148.856702 167.001988v605.969689c0 15.185797-4.052331 29.410732-11.133466 41.672166h115.554096c11.551232 0 20.909192 9.274407 20.909192 20.888304 0 11.530344-9.295295 20.888304-20.888304 20.888304H1002.638576v20.992745c0 15.185797-4.052331 29.410732-11.133466 41.672166h11.196131c11.488567 0 20.825639 9.274407 20.825639 20.888303 0 11.530344-9.462402 20.888304-20.825639 20.888304h-109.893365c9.545955 16.000441 7.478013 36.972297-6.41271 50.863019a41.672166 41.672166 0 0 1-59.072122 0L776.460024 960.861969z m76.367638-41.776607h66.424806c22.977134 0 41.609501-18.59059 41.609501-41.881049V270.461756c0-22.559368-18.047494-40.690416-40.314426-40.690416H416.303892c-22.266932 0-40.314426 18.214601-40.314426 40.690416v606.742557c0 23.123352 18.799473 41.881049 41.588613 41.881049h317.084449l-10.736588-10.757477a41.693054 41.693054 0 0 1-10.861918-40.377091l-19.718558-19.739447A146.259902 146.259902 0 0 1 502.363703 627.693525a146.218126 146.218126 0 0 1 220.517822 190.981761l19.739447 19.739447a41.630389 41.630389 0 0 1 40.377091 10.841029L852.827662 919.085362zM1002.638576 814.643843h62.852906A41.797496 41.797496 0 0 0 1107.080095 772.867236V167.106429c0-23.14424-18.632367-41.776607-41.588613-41.776607H563.775316A41.797496 41.797496 0 0 0 522.207592 167.106429v20.888304h396.794216A83.448773 83.448773 0 0 1 1002.638576 271.443506V814.643843zM266.325872 46.998683h31.123572c8.773088 0 15.875111 6.955805 15.875111 15.666228 0 8.647758-7.102023 15.666228-15.875111 15.666228h-31.123572v31.123572c0 8.773088-6.955805 15.875111-15.666228 15.875111a15.770669 15.770669 0 0 1-15.666228-15.875111V78.331139H203.869844A15.728893 15.728893 0 0 1 187.994733 62.664911c0-8.647758 7.102023-15.666228 15.875111-15.666228h31.123572V15.875111c0-8.773088 6.955805-15.875111 15.666228-15.875111 8.647758 0 15.666228 7.102023 15.666228 15.875111v31.123572zM20.888304 939.973665c0-11.530344 9.462402-20.888304 20.825638-20.888303h125.455152c11.488567 0 20.825639 9.274407 20.825639 20.888303 0 11.530344-9.462402 20.888304-20.825639 20.888304H41.713942A20.80475 20.80475 0 0 1 20.888304 939.973665z m658.733544-135.021995a104.441518 104.441518 0 1 0-147.722083-147.722083 104.441518 104.441518 0 0 0 147.722083 147.722083zM459.542681 313.324555a20.888304 20.888304 0 0 1 20.867415-20.888304H710.202325a20.888304 20.888304 0 1 1 0 41.776608H480.430984A20.825639 20.825639 0 0 1 459.542681 313.324555z m0 104.441518c0-11.530344 9.295295-20.888304 20.742085-20.888303h334.505295c11.44679 0 20.742086 9.274407 20.742086 20.888303 0 11.530344-9.295295 20.888304-20.742086 20.888304H480.284766A20.762974 20.762974 0 0 1 459.542681 417.766073z m0 104.441519c0-11.530344 9.316183-20.888304 20.846527-20.888304h146.301679c11.509455 0 20.846527 9.274407 20.846527 20.888304 0 11.530344-9.316183 20.888304-20.846527 20.888303h-146.301679A20.80475 20.80475 0 0 1 459.542681 522.207592zM62.664911 396.87777a62.664911 62.664911 0 1 1 0-125.329822 62.664911 62.664911 0 0 1 0 125.329822z m0-31.332456a31.332456 31.332456 0 1 0 0-62.664911 31.332456 31.332456 0 0 0 0 62.664911zM1357.739739 271.547948a62.664911 62.664911 0 1 1 0-125.329822 62.664911 62.664911 0 0 1 0 125.329822z m0-31.332456a31.332456 31.332456 0 1 0 0-62.664911 31.332456 31.332456 0 0 0 0 62.664911z" fill="#8A96A3" p-id="2626" /></svg>
                    <div style="font-size: 14px; color: #555; ">{{ $t('未发现笔记') }}</div>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template slot="paneR">
            <div v-loading="textContextLoading" class="flexible-list-right">
              <div class="top-title-box">
                <div class="top-title">
                  <div style="width: 50px;line-height: 2.1;font-size: 16px;font-weight: bold;">{{ $t('标题') }}:</div>
                  <el-input v-model="form.title" icon="el-icon-search" class="title-input" :placeholder="$t('无标题笔记')" style="border: none" />
                </div>
                <div class="btn">
                  <i :class="form.type" />
                  <el-button size="mini" :disabled="isEmpty(form.id)" @click="historyInfo(form.id)">{{ $t('版本') }}</el-button>
                  <el-button size="mini" :disabled="isEmpty(form.id)" @click="openRemind(form)">{{ $t('提醒') }}</el-button>
                  <el-popover v-model="iconColorVisible" placement="bottom" :height="(31.375 * (singColorOptions.length + 1)) + 'px'" style="margin-left: 10px;" trigger="click">
                    <div>
                      <el-radio-group v-model="form.color" type="vertical" @change="updateLabelTypes();iconColorVisible = false">
                        <el-radio class="radio-tag-btn" label="">
                          <span style="font-weight: lighter; font-size: 20px; position: absolute; bottom: 13px; ">○<span style="position: absolute;left: 6.9px;">/</span></span>
                        </el-radio>
                        <el-radio
                          v-for="dict in singColorOptions"
                          :key="dict.id"
                          class="radio-tag-btn"
                          :label="dict.dictValue"
                        ><span :style="{ 'color': dict.dictValue, 'font-weight': 'lighter', 'font-size': '20px', 'position': 'absolute', 'bottom': '13px' }">●</span></el-radio>
                      </el-radio-group>
                    </div>
                    <el-button slot="reference" size="mini" :disabled="isEmpty(form.id)">{{ $t('标记') }}</el-button>
                  </el-popover>
                  <el-popover v-model="iconTypeVisible" placement="bottom" :height="(31.375 * (createTypeOptions.length + 1)) + 'px'" style="margin-left: 10px;" trigger="click">
                    <div>
                      <el-radio-group v-model="form.type" type="vertical" @change="updateTypeByIds();iconTypeVisible = false">
                        <el-radio class="radio-tag-btn" label="">{{ $t('个人笔记') }}</el-radio>
                        <el-radio
                          v-for="dict in createTypeOptions"
                          :key="dict.id"
                          class="radio-tag-btn"
                          :label="dict.dictValue"
                        >{{ $t(dict.dictLabel) }}</el-radio>
                      </el-radio-group>
                    </div>
                    <el-button slot="reference" size="mini" :disabled="form.userId !== $store.state.user.userId">{{ $t('分类') }}</el-button>
                  </el-popover>
                  <el-button size="mini" :disabled="form.userId !== $store.state.user.userId" style="margin-left: 10px;" @click="shareReady">{{ $t('分享') }}</el-button>
                  <el-button size="mini" :disabled="form.shareEdit === 'N' && form.userId !== $store.state.user.userId" style="margin-left: 10px;" @click="saveText()">{{ isEmpty(form.id) ? $t('新建') : $t('保存') }}</el-button>
                </div>
              </div>
              <!-- 正文 -->
              <div class="markdown-text" style="padding-right: 5px;">
                <markdownContent ref="markdownContent" :value="form.text" height="calc(100vh - 350px)" @change="setText($event)" />
              </div>
              <!-- 标签 -->
              <div class="tag-main">
                <div v-show="false">
                  isCurrentNotes: {{ isCurrentNotes }} |
                  isCurrentTag: {{ isCurrentTag }} |
                  isCurrentShare: {{ isCurrentShare }} |
                  isCurrentFollow:  {{ isCurrentFollow }} |
                  isCurrentSearch: {{ isCurrentSearch }}
                </div>
                <div>
                  <el-tag
                    v-for="tag in dynamicTags"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-select
                    v-if="inputVisible"
                    ref="saveTagInput"
                    v-model="inputValue"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :placeholder="$t('请输入标签')"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                  >
                    <el-option
                      v-for="item in tagOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                  <el-button v-else :disabled="isEmpty(form.id)" class="button-new-tag" size="small" @click="showInput" @keyup.enter.native="showInput">+</el-button>
                </div>
              </div>
            </div>
          </template>
        </split-pane>
      </template>
    </split-pane>

    <!-- 分享 -->
    <el-dialog :title="$t('分享')" :visible.sync="shareOpen" width="600" style="height: 500px; width: 600px; margin: auto !important;" :close-on-click-modal="false" custom-class="dialogForm" append-to-body>
      <div v-loading="shareOpenLoading">
        <el-form ref="ruleForm" :model="form" :rules="rules" :disabled="form.userId !== $store.state.user.userId" label-width="120px" class="dataForm">
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('开启状态')" prop="shareStatus">
                <el-switch v-model="form.shareStatus" active-value="Y" inactive-value="N" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('能否编辑')" prop="shareEdit">
                <el-switch v-model="form.shareEdit" active-value="Y" inactive-value="N" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('分享人员')" prop="shareUserId">
                <UserSelect v-model="form.shareUserId" :multiple="true" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-if="form.userId === $store.state.user.userId" slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="shareOpen = false">{{ $t('取消') }}</el-button>
          <el-button type="primary" @click="saveShare">{{ $t('保存') }}</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 历史 -->
    <el-dialog :title="$t('历史')" :visible.sync="historyOpen" :close-on-click-modal="false" style="padding: 0!important;" custom-class="dialogForm dialog-history-div" append-to-body @close="historyQuery.pageNum = 1">
      <div v-loading="historyLoading">
        <split-pane :default-percent="18" :min-percent="12" split="vertical" @resize="resize">
          <template slot="paneL">
            <div style="overflow: auto;height: 100%;">
              <div v-for="(item, index) in historyList" :key="index" class="history-div-list" @click="choiceCurrentHistory(item)">
                <div style="font-size: 14px;font-weight: bold;">{{ formatDate(parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}')) }}</div>
                <div style="font-size: 12px;color: #555;">{{ item.deptName }} - {{ item.nickName }}</div>
              </div>
            </div>
          </template>
          <template slot="paneR">
            <div class="top-title-box">
              <div class="top-title" style="text-align: center;font-size: 16px;font-weight: bold;">
                {{ choiceCurrentHistoryTitle }}
              </div>
              <div>
                <markdownContent ref="markdownContent" :value="choiceCurrentHistoryText" height="calc(100vh - 330px)" />
              </div>
            </div>
          </template>
        </split-pane>
      </div>
    </el-dialog>

    <!-- 提醒设置 -->
    <el-dialog :title="$t('项目提醒')" :visible.sync="remindOpen" style="width: 66%;height: 78%;top: 10%;left: 14%;z-index: 2005;" :destroy-on-close="true" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <remindEvent ref="remindEvent" :is-show-user="true" reminder-type="sys_user_notes" />
    </el-dialog>
  </div>
</template>

<script>
import {
  collectionCancel,
  collectionSave,
  delGroupById,
  delTextById,
  getUserTag,
  group,
  groupSave,
  historyById,
  historyList,
  iFollow,
  moveText,
  saveTag,
  searchText,
  shareText,
  shareToMe,
  textByGroupId,
  textById,
  textByTag,
  textSave,
  updateLabelType,
  updateTypeById
} from '@/api/oa/notes/sysUserNotes'
import markdownContent from '@/components/markdown/index.vue'
import remindEvent from '@/components/remind/sysRemindEvent.vue'
export default {
  components: {
    markdownContent,
    remindEvent
  },
  data() {
    return {
      form: {
        shareEdit: undefined,
        shareStatus: undefined
      },
      total: 0,
      loading: false,
      shareOpenLoading: false,
      scrollLoading: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      prohibitClickingIds: ['notes', 'follow', 'share', 'tag'],
      dirIds: ['notes', 'tag'],
      resize: 10,
      inputSearch: undefined,
      selectSearch: 'title',
      noteData: [],
      textList: [],
      selectGroupId: undefined,
      editId: undefined,
      pageNum: 1,
      tagOptions: [],
      createTypeOptions: [],
      singColorOptions: [],
      querySelectOption: [],
      iconTypeVisible: false,
      iconColorVisible: false,
      addGroupBtnLoading: false,
      addTextBtnLoading: false,
      textContextLoading: false,
      delTextBtnLoading: false,
      shareOpen: false,
      historyOpen: false,
      historyQuery: {
        title: undefined,
        text: undefined,
        textId: undefined
      },
      historyList: [],
      historyLoading: false,
      choiceCurrentHistoryTitle: '',
      choiceCurrentHistoryText: '',
      historyTotal: 0,
      dynamicTags: [],
      moveTextSelect: [],
      inputVisible: false,
      inputValue: '',
      rules: {
        shareEdit: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        shareStatus: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        shareUserId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      isCurrentNotes: true,
      isCurrentTag: false,
      isCurrentFollow: false,
      isCurrentShare: false,
      isCurrentSearch: false,
      remindOpen: false
    }
  },
  computed: {
    noMore() {
      return this.total <= this.textList.length
    },
    disabled() {
      return this.scrollLoading || this.noMore || this.loading
    }
  },
  watch: {
    'form.type': {
      handler(val) {
        console.log(val)
      }
    },
    'form.text': {
      handler(val) {
        if (this.isEmpty(val)) {
          this.form.text = ''
        }
      },
      deep: true
    },
    noteData: {
      handler(val) {
        // 树如果变动, 移动下拉同步更行
        if (val) {
          this.moveTextSelect = []
          val.forEach(item => {
            if (item.id === 'notes') {
              console.log(item)
              item.children && item.children.forEach(t => {
                this.moveTextSelect.push(t)
              })
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDicts('user_notes_create_type').then(response => {
      this.createTypeOptions = response.data
    })
    this.getDicts('user_notes_sing_color').then(response => {
      this.singColorOptions = response.data
    })
  },
  mounted() {
    this.init()
    this.initTabSelect()
    // 监听键盘事件
    document.addEventListener('keydown', this.handleKeydown)
  },
  beforeDestroy() {
    // 移除事件监听以防止内存泄漏
    document.removeEventListener('keydown', this.handleKeydown)
  },
  methods: {
    init() {
      this.loading = true
      group().then(response => {
        this.noteData = response.data
        // 默认点击一下未分组
        this.noteData[0].children && this.noteData[0].children.forEach(item => {
          if (item.name === '未分组') {
            this.viewNotes(item.id, true)
          }
        })
        this.tagOptions = []
        this.noteData && this.noteData.forEach(item => {
          if (item.bolong === 'tag') {
            item.children && item.children.forEach(item2 => {
              this.tagOptions.push(item2.name)
            })
          }
        })
      })
    },
    /**
     * 滑动加载
     */
    load() {
      this.pageNum++
      this.scrollLoading = true
      if (this.selectGroupId && this.isCurrentNotes) {
        this.viewNotes(this.selectGroupId, false)
      } else if (this.isCurrentTag) {
        this.viewTag(this.currentTagData, false)
      } else if (this.isCurrentShare) {
        this.viewShare(false)
      } else if (this.isCurrentFollow) {
        this.viewFollow(false)
      } else if (this.isCurrentSearch) {
        this.querySearch(false)
      } else {
        this.pageNum = 1
        this.scrollLoading = false
      }
    },
    /**
     * 初始化当前已有的标签
     */
    initTabSelect() {},
    /**
     * 搜索
     */
    querySearch(reload) {
      console.log('搜索')
      this.isCurrentSearch = true
      this.isCurrentNotes = this.isCurrentTag = this.isCurrentFollow = this.isCurrentShare = false
      if (reload) {
        this.pageNum = 1
        this.textList = []
      }
      this.loading = !this.scrollLoading
      searchText({ queryType: this.selectSearch, text: this.inputSearch, pageNum: this.pageNum, pageSize: 20 }).then(response => {
        response.rows.forEach(item => {
          this.textList.push(item)
        })
        this.total = response.total
        this.loading = false
        this.scrollLoading = false
      }).catch(() => {
        this.loading = false
        this.scrollLoading = false
      })
    },
    /**
     * 清空搜索
     */
    clearQuerySearch() {
      this.inputSearch = undefined
      this.selectSearch = 'title'
      this.init()
    },
    /**
     * 搜索切换下拉
     */
    changeSelectQuery() {
      this.querySelectOption = []
      if (this.selectSearch === 'tag') {
        this.noteData && this.noteData.forEach(item => {
          if (item.belong === 'tag') {
            item.children && item.children.forEach(item => {
              this.querySelectOption.push({ label: item.name, value: item.name })
            })
          }
        })
      } else if (this.selectSearch === 'type') {
        this.createTypeOptions.forEach(item => {
          this.querySelectOption.push({ label: item.dictLabel, value: item.dictValue })
        })
      } else if (this.selectSearch === 'color') {
        this.singColorOptions.forEach(item => {
          this.querySelectOption.push({ label: item.dictLabel, value: item.dictValue, color: item.dictValue })
        })
      }
    },
    /**
     * 拦截crtl+s 保存当前text
     */
    handleKeydown() {
      const isCtrlKey = event.ctrlKey || event.metaKey // event.metaKey 在 Mac 上等同于 Command 键
      if (isCtrlKey && event.key === 's') {
        event.preventDefault()
        this.saveText()
      }
    },
    /**
     * 添加组
     */
    addGroup() {
      this.addGroupBtnLoading = true
      groupSave({ name: '新建分组' }).then(response => {
        this.msgSuccess(response.msg)
        response.data.belong = 'notes'
        this.noteData[0].children.push(response.data)
        this.addGroupBtnLoading = false
      })
    },
    /**
     * 删除分组目录
     */
    removeGroup(data) {
      delGroupById(data.id).then(() => {
        this.noteData[0].children && this.noteData[0].children.forEach((item, index) => {
          if (item.id === data.id) {
            this.noteData[0].children.splice(index, 1)
          }
        })
        this.msgSuccess(this.$t('删除成功'))
      }).catch(() => {
        this.msgError(this.$t('操作失败!'))
      })
    },
    /**
     * 编辑组名
     */
    editGroup(data) {
      this.$nextTick(() => {
        this.editId = data.id
      })
    },
    /**
     * 修改组名
     */
    blurGroup(data) {
      if (!this.isEmpty(data.name)) {
        this.$nextTick(() => {
          this.editId = undefined
        })
        groupSave(data).catch(() => {
          this.msgError(this.$t('操作失败!'))
        })
      }
    },
    /**
     * 点击分组获取改组下的笔记列表的
     */
    viewNotes(groupId, reload) {
      if (reload) {
        this.textList = []
        this.pageNum = 1
      }
      this.selectGroupId = groupId
      this.loading = !this.scrollLoading
      textByGroupId({ groupId: groupId, pageNum: this.pageNum, pageSize: 20 }).then(response => {
        response.rows.forEach(item => {
          this.textList.push(item)
        })
        this.total = response.total
        this.loading = false
        this.scrollLoading = false
      })
    },
    /**
     * 根据标签获取改标签下相关的笔记
     */
    viewTag(data, reload) {
      console.log(data, '点击标签')
      if (reload) {
        this.pageNum = 1
        this.textList = []
      }
      this.currentTagData = data
      this.loading = !this.scrollLoading
      textByTag({ tag: data.name, pageNum: this.pageNum, pageSize: 20 }).then(response => {
        response.rows.forEach(item => {
          this.textList.push(item)
        })
        this.total = response.total
        this.loading = false
        this.scrollLoading = false
      })
    },
    /**
     * 判断当前点击的是否为某个节点
     */
    recordNodes(data) {
      console.log('记录节点')
      this.isCurrentFollow = data.belong === 'follow'
      this.isCurrentShare = data.belong === 'share'
      this.isCurrentTag = data.belong === 'tag'
      this.isCurrentNotes = data.belong === 'notes'
      this.isCurrentSearch = false
      this.inputSearch = undefined
      this.selectSearch = 'title'
      this.pageNum = 1
    },
    /**
     * 分享个我的笔记
     */
    viewShare(reload) {
      if (reload) {
        this.pageNum = 1
        this.textList = []
      }
      this.loading = !this.scrollLoading
      shareToMe({ pageNum: this.pageNum, pageSize: 20 }).then(response => {
        response.rows.forEach(item => {
          this.textList.push(item)
        })
        this.total = response.total
        this.loading = false
        this.scrollLoading = false
      })
    },
    /**
     * 关注的笔记
     */
    viewFollow(reload) {
      if (reload) {
        this.pageNum = 1
        this.textList = []
      }
      this.loading = !this.scrollLoading
      iFollow({ pageNum: this.pageNum, pageSize: 20 }).then(response => {
        response.rows.forEach(item => {
          this.textList.push(item)
        })
        this.total = response.total
        this.loading = false
        this.scrollLoading = false
      })
    },
    /**
     * 查看text
     */
    viewText(text) {
      console.log('查看笔记')
      this.textContextLoading = true
      this.dynamicTags = []
      textById(text.id).then(response => {
        this.form = response.data
        if (!this.isEmpty(this.form) && !this.isEmpty(this.form.tag)) {
          const tag = this.form.tag.split(',')
          tag.forEach(t => {
            this.dynamicTags.push(t)
          })
        }
        this.textContextLoading = false
        this.$forceUpdate()
      })
    },
    /**
     * 创建新的笔记
     */
    addText(type) {
      this.addTextBtnLoading = true
      textSave({ groupId: this.selectGroupId, title: '无标题笔记', type: type }).then(response => {
        this.viewNotes(this.selectGroupId, true)
        this.form = response.data
        this.addTextBtnLoading = false
      })
    },
    /**
     * 保存正在编辑的笔记
     */
    saveText() {
      console.log('保存笔记', this.form)
      if (this.form && this.form.shareEdit === 'N' && this.form.userId !== this.$store.state.user.userId) {
        this.msgError('该笔记来自他人分享且没有开启可编辑权限!')
        return
      }
      var flag = true
      this.textList && this.textList.forEach((item, index) => {
        if (item.id === this.form.id) {
          this.form.groupId = this.selectGroupId || this.$store.state.user.userId
          this.form.title = this.isEmpty(this.form.title) ? '无标题笔记' : this.form.title
          this.textList[index] = JSON.parse(JSON.stringify(this.form))
          this.$forceUpdate()
          flag = false
        }
      })
      if (flag) {
        if (!this.isEmpty(this.form.id)) {
          flag = false
          this.form.groupId = this.selectGroupId || this.$store.state.user.userId
          this.form.title = this.isEmpty(this.form.title) ? '无标题笔记' : this.form.title
        } else {
          this.form = {
            groupId: this.selectGroupId || this.$store.state.user.userId,
            title: this.isEmpty(this.form.title) ? '无标题笔记' : this.form.title,
            text: this.form.text
          }
        }
      }
      textSave(this.form).then(response => {
        response.data.userId = response.data.createBy.id
        this.form = response.data
        if (flag) {
          response.data.collection = 'N'
          this.textList.unshift(JSON.parse(JSON.stringify(response.data)))
          this.msgSuccess(this.$t('新建成功'))
        } else {
          this.msgSuccess(this.$t('修改成功'))
        }
      })
    },
    /**
     * 删除笔记
     */
    delText(data) {
      var _this = this
      this.$confirm(this.$t('此操作将永久删除该文件, 是否继续?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        _this.delTextBtnLoading = false
        _this.textList.forEach((item, index) => {
          if (item.id === data.id) {
            _this.total -= 1
            _this.textList.splice(index, 1)
            _this.form = {}
          }
        })
        delTextById(data.id).then(() => {
          _this.delTextBtnLoading = false
        }).catch(() => {
          _this.msgError(_this.$t('删除失败!'))
          _this.delTextBtnLoading = false
        })
      }).catch(() => {
      })
    },
    /**
     * 移动笔记
     */
    moveText(text, data) {
      moveText(text.id, data.id).then(response => {
        if (response.msg === '操作成功') {
          this.msgSuccess(this.$t(response.msg))
        } else {
          this.msgError(this.$t(response.msg))
        }
        this.textList && this.textList.forEach((item, index) => {
          if (item.id === text.id) {
            this.total -= 1
            this.textList.splice(index, 1)
          }
        })
      })
    },
    /**
     * 收藏
     */
    addCollection(data) {
      collectionSave({ textId: data.id })
      this.form.collection = 'Y'
      this.textList.forEach((item, index) => {
        if (item.id === data.id) {
          this.$set(this.textList[index], 'collection', 'Y')
        }
      })
      this.$forceUpdate()
    },
    /**
     * 取消收藏
     */
    delCollection(data) {
      console.log('取消收藏')
      collectionCancel({ textId: data.id })
      this.form.collection = 'N'
      this.textList.forEach((item, index) => {
        if (item.id === data.id) {
          this.$set(this.textList[index], 'collection', 'N')
        }
      })
      // 关注列表取消的, 则在列表去掉该行
      if (this.isCurrentFollow) {
        this.textList.forEach((item, index) => {
          if (item.id === data.id) {
            this.total -= 1
            this.textList.splice(index, 1)
          }
        })
      }
      this.$forceUpdate()
    },
    /**
     * 删除标签
     */
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      this.refreshTabs()
    },
    /**
     * 添加标签
     */
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /**
     * 提交标签
     */
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        inputValue.forEach(e => {
          this.dynamicTags.push(e)
        })
      }
      this.inputVisible = false
      this.inputValue = ''
      // 刷新标签
      this.refreshTabs()
    },
    /**
     * 刷新标签
     */
    refreshTabs() {
      this.dynamicTags = [...new Set(this.dynamicTags)]
      this.form.tag = this.dynamicTags.join(',')
      saveTag(this.form).then(() => {
        getUserTag().then(response => {
          this.tagOptions = []
          response.data.forEach(tag => {
            this.tagOptions.push(tag.name)
          })
          this.noteData && this.noteData.forEach((item, index) => {
            if (item.id === 'tag') {
              this.noteData[index].children = response.data
            }
          })
        })
      }).catch(() => {
        this.msgError(this.$t('标签保存异常!'))
      })
    },
    /**
     * 打开分享页面
     */
    shareReady() {
      console.log('打开分享')
      this.shareOpen = true
      if (!this.isEmpty(this.form.shareUserId) && typeof this.form.shareUserId === 'string') {
        this.form.shareUserId = this.form.shareUserId.split(',')
      }
    },
    /**
     * 保存分享
     */
    saveShare() {
      this.shareOpenLoading = true
      const formBak = JSON.parse(JSON.stringify(this.form))
      this.form.shareUserId = this.form.shareUserId.join(',')
      shareText(this.form).then(response => {
        this.msgSuccess(this.$t(response.msg))
        this.form.shareUserId = formBak.shareUserId
        this.shareOpenLoading = false
        this.shareOpen = false
      }).catch(() => {
        this.shareOpenLoading = false
        this.msgError(this.$t('操作失败!'))
      })
    },
    /**
     * 修改分类
     */
    updateTypeByIds() {
      this.textList.forEach(item => {
        if (item.id === this.form.id) {
          item.type = this.form.type
        }
      })
      updateTypeById(this.form.id, this.form.type).then(response => {
        this.msgSuccess(response.msg)
      }).catch(() => {
        this.msgError(this.$t('操作失败!'))
      })
    },
    /**
     * 修改表示(颜色)
     */
    updateLabelTypes() {
      this.textList.forEach(item => {
        if (item.id === this.form.id) {
          item.color = this.form.color
        }
      })
      updateLabelType({ id: this.form.id, color: this.form.color }).then(response => {
        this.msgSuccess(response.msg)
      }).catch(() => {
        this.msgError(this.$t('操作失败!'))
      })
    },
    // 提醒设置
    openRemind(data) {
      this.remindOpen = true
      this.$nextTick(() => {
        this.$refs.remindEvent.init(data.id + this.$store.state.user.userId)
      })
    },
    /**
     * 笔记历史
     */
    historyInfo(id) {
      this.historyOpen = true
      this.historyQuery.textId = id
      this.historyLoading = true
      historyList(this.historyQuery).then(response => {
        this.historyList = response.rows
        this.historyTotal = response.total
        this.historyLoading = false
      }).catch(() => {
        this.historyLoading = false
        this.msgError(this.$t('操作失败!'))
      })
    },
    /**
     * 查看某个历史记录
     */
    choiceCurrentHistory(row) {
      this.historyLoading = true
      historyById(row.id).then(response => {
        this.choiceCurrentHistoryTitle = response.data.title
        this.choiceCurrentHistoryText = response.data.text
        this.historyLoading = false
      }).catch(() => {
        this.historyLoading = false
        this.msgError(this.$t('操作失败!'))
      })
    },
    setText(val) {
      this.form.text = val
    },
    /**
     * 历史输出格式化时间
     */
    formatDate(time) {
      // 如果是今天 只返回时间
      var time1 = new Date()
      var time2 = new Date(time)
      if ((time1.getFullYear() + '-' + (time1.getMonth() + 1) + '-' + time1.getDate()) === (time2.getFullYear() + '-' + (time2.getMonth() + 1) + '-' + time2.getDate())) {
        return this.$t('今天') + ' ' + time2.getHours() + ':' + time2.getMinutes()
      } else {
        return time
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tag-main {
  height: calc(100vh - (100vh - 100px));
  background: white;
  border-top: 1px solid rgb(216, 216, 216);
  padding: 15px;
  overflow: auto;

}
/deep/.vuepress-markdown-body li{
  list-style: unset;
}
.noteView {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background: white;
}

.expand-layout {
  height: 100%;
  /deep/ .el-tree {
    background: transparent;
    color: #4e5a70;
    height: calc(100% - 65px);
    overflow: auto;
    padding: 0 0 0 6px;

    .el-tree-node__content {
      height: 30px;

      &:hover {
        background: #F0F3F5;
      }
    }
  }
}

.flexible-list-left {
  height: 100%;
  background: #fff;
  border-radius: 12px 0 0 12px;
  box-shadow: -2px 0 4px rgba(0, 0, 0, 0.02);

  .list-search {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 45px;
    padding: 15px;

    ::-webkit-input-placeholder {
      color: #A9B2C2;
    }
  }

  .list-view-item {
    height: calc(100% - 73px);
    overflow: auto;

    .list-li {
      position: relative;
      cursor: pointer;
      padding: 15px;
      box-sizing: border-box;
      border-top: 1px solid #f0f3f5;
      overflow: hidden;

      .title {

        .file-name-wrap {
          display: flex;
          align-items: center;

          .file-name {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin: 0 5px;
            font-size: 13px;
            color: #232d47;
            font-weight: 500;
            position: relative;
          }
        }

        .date-size {
          color: #a9b2c2;
          margin-top: 8px;
          font-size: 12px;
          .file-size {
            color: #888888;
          }
        }
      }
    }
  }
}

.flexible-list-right {
  flex: 1;
  background: #fff;
  border-left: 1px solid #f0f3f5;

  .top-title-box {
    display: flex;
    align-items: center;
    height: 45px;
    justify-content: space-between;
    position: relative;
    padding: 0 24px;
    border-bottom: 1px solid #f0f3f5;

    .top-title {
      display: flex;
      h2 {
        margin: 0;
      }
    }

    .btn {
      .note-btn {
        display: inline-block;
        height: 28px;
        line-height: 28px;
        padding: 0 16px;
        font-size: 14px;
        color: #4e5a70;
        text-align: center;
        cursor: pointer;
        background-color: #f0f3f5;
        border-radius: 4px;
      }
    }
  }
}
.el-icon-s-operation {
  margin-left: 10px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
}
.more-dir {
  border-bottom: 1px solid #ececec;
}
.more-dir ul {
  background: #fff;
  display: flex;
}

.more-dir li {
  height: 45px;
  line-height: 45px;
  cursor: pointer;
  font-size: 15px;
  color: #606266;
  flex: 1;
  text-align: center;
}
.more-dir li i{
  font-weight: bold;
}
.more-dir li:first-child {
  border-right: 1px solid #ececec;
}
/deep/.material-input__component .iconClass .material-label {
  font-size: 14px;
  margin-top: 10px;
  left: 20px;
}
/deep/.material-input__component {
  margin-top: 0px;
}
/deep/.title-input input {
  border-top: none !important;
  border-left: none !important;
  border-right: none !important;
  border-radius: 0;
  font-weight: bold;
  font-size: 16px;
  width: 120%;
}
/deep/.scrollbar__wrap{
  position: unset!important;
}
/deep/.el-tag--medium {
  height: 28px;
  line-height: 26px;
  margin-right: 10px;
}
.tree-node-btn {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
label.el-radio.radio-tag-btn {
  padding: 15px;
  display: block;
}
/deep/.el-search-select-left input {
  height: 28px;
  border: 1px solid #d1d0d1;
  border-radius: 5px 0 0 5px;
  background: #f5f5f5;
}
/deep/.el-search-select-right input {
  height: 28px;
  border: 1px solid #d1d0d1;
  border-radius: 0 5px 5px 0;
}
.history-div-list {
  padding: 10px;
  cursor: pointer;
}
.history-div-list:hover {
  background: #e8e8e8;
}
/deep/.dialog-history-div.el-dialog__body {
  padding: 0 !important;
}
</style>

